// import Fly from 'flyio/dist/npm/wx';
const Fly = require("flyio.js");
const fly = new Fly();

//设置超时
fly.config.timeout = 20000;

// 获取白名单
import whiteList from './whiteList';

//添加请求拦截器
fly.interceptors.request.use((request) => {
  // console.log('进入fly-request', request);
  wx.showLoading({
    'title': '加载中',
    'mask': true
  });
  // 不显示加载页面的接口
  if (whiteList.loading.indexOf(request.url) === -1) {
    // 隐藏loading遮罩
    wx.hideLoading();
  }
  // 请求资源服务器时，不添加token
  if (whiteList.nullHeaderToken.indexOf(request.url) !== -1) {
    request.timeout = 30000; // 请求超时
    request.headers = {
      'content-type': 'application/json',
      'X-Tag': 'flyio'
    };
    console.log('nullHeaderToken()')
    return request;
  }
  fly.lock();//锁住请求
  // 延迟发请求 等 getStorageSync 存储
  if (wx.getStorageSync('Authorization')) {
    // 给所有请求添加自定义header
    request.timeout = 30000;
    request.headers = {
      'content-type': 'application/json',
      'X-Tag': 'flyio',
      'X-Auth-Token':  wx.getStorageSync('Authorization')
      // 'Authorization': 'Bearer ' + wx.getStorageSync('Authorization')
    };
    fly.unlock();//解锁请求
    return request;
  } else {
    console.log('没有token跳转登录');
    setTimeout(() => {
      wx.redirectTo({
        url: '../login/login'
      });
    }, 300)
  }
}, (error, promise) => {
  // Do something with request error
  console.log(error); // for debug
  promise.reject(error)
});

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response,promise) => {
    wx.hideLoading();
    console.log('interceptors数据', response.data);
    const res = response.data
    if (res.code && res.code !== 0) {
      let msg = ''
      if (res.code === 10000) {
        msg = '未配置路由权限,请联系管理员'
      } else if (res.code === 10003) {
        msg = '该账户无权限，请联系管理员'
      } else if (res.code === 10005) {
        msg = '后台系统错误'
      } else {
        msg = res.msg
      }
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      });
    } else {
      //只将请求结果的data字段返回
      return response.data
    }
    return Promise.reject('error')
  },
  (err, promise) => {
    console.log('-err', err);
    wx.hideLoading();
    let msg = '';
    if (err.status === 0) {
      msg = '网络连接异常'
    } else if (err.status === 1) {
      msg = '网络连接超时'
    } else if (err.status === 401) {
      msg = '用户未登录'
    } else {
      if (err.response.data.message) {
        msg = err.response.data.msg
      } else {
        msg = '请求数据失败,请稍后再试'
      }
    }
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
    setTimeout(() => {
      console.log('fly.interceptors.err-toLogin')
      wx.redirectTo({
        url: '../login/login'
      });
    }, 500)
    return promise.resolve(err)
  }
);
// Vue.prototype.$http=fly //将fly实例挂在vue原型上

export default fly